package com.tzu.ft.ui.comps;

import com.tzu.ft.base.FTConfig;
import com.tzu.ft.ui.utils.FTUITools;
import com.tzu.utils.StringTools;
import com.tzu.ssl.KeyInfo;
import com.tzu.ssl.SSLTools;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;

/**
 * 设置对话框
 */
public class SettingDialog extends JDialog {

    private static final long serialVersionUID = 1L;

    public static final int NO = 0;
    public static final int YES = 1;

    /**
     * 确认信息
     */
    public static void showConfirmInfo(Frame frame) {
        SettingDialog dialog = new SettingDialog(frame);
        dialog.closeInstance();
    }

    private SettingDialog instence;

    public SettingDialog() {
        init(null);
    }

    public SettingDialog(Frame frame) {
        super(frame);
        init(frame);
    }

    private JTextField textField_confipath;
    private JTextField textField_keypass;

    private JButton btnNewButton_createssl;
    private JFormattedTextField textField_maxthreads;
    private JFormattedTextField textField_buffersize;

    private void init(Frame frame) {
        instence = this;
        // 窗口大小
        setSize(650, 500);
        if (null != frame) {
            setLocation(frame.getX() + 30, frame.getY() + 30);
        }
        // 不可改变大小
        setResizable(false);
        // 设置弹出阻塞，父窗口将被锁定
        setModal(true);
        // 初始化
        setTitle("设置");
        getContentPane().setLayout(null);
        // 禁用关闭按钮
        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setBounds(0, 0, 644, 471);
        getContentPane().add(panel);
        panel.setLayout(null);

        JButton btnNewButton = new JButton("确定");
        btnNewButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                boolean saveres = saveConfig();
                if (saveres) {
                    setVisible(false);
                }
            }
        });
        btnNewButton.setBounds(105, 431, 200, 30);
        panel.add(btnNewButton);

        JButton btnNewButton_1 = new JButton("取消");
        btnNewButton_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        });
        btnNewButton_1.setBounds(358, 431, 200, 30);
        panel.add(btnNewButton_1);

        JLabel lblNewLabel = new JLabel("配置文件路径：");
        lblNewLabel.setBounds(10, 25, 105, 25);
        panel.add(lblNewLabel);

        textField_confipath = new JTextField("- 未设定 -");
        textField_confipath.setBounds(120, 25, 432, 25);
//		textField_confipath.setEnabled(false);
        panel.add(textField_confipath);

        JLabel label_ssl = new JLabel("SSL证书密码：");
        label_ssl.setBounds(10, 79, 105, 25);
        panel.add(label_ssl);

        textField_keypass = new JTextField("");
        textField_keypass.setBounds(120, 79, 185, 25);
        panel.add(textField_keypass);

        btnNewButton_createssl = new JButton("生成证书");
        btnNewButton_createssl.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                createSsl();
            }
        });
        btnNewButton_createssl.setBounds(315, 79, 150, 25);
        panel.add(btnNewButton_createssl);

        JButton btnNewButton_openssl = new JButton("查看证书");
        btnNewButton_openssl.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String sslpath = FTConfig.getSslPath();
                try {
                    if (Desktop.isDesktopSupported()) {
                        Desktop.getDesktop().open(new File(sslpath));
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
        btnNewButton_openssl.setBounds(475, 79, 150, 25);
        panel.add(btnNewButton_openssl);

        JLabel label_threads = new JLabel("并行任务数：");
        label_threads.setBounds(10, 129, 105, 25);
        panel.add(label_threads);

        //设定输入格式
        NumberFormat numberformat_maxthreads = NumberFormat.getNumberInstance();
        numberformat_maxthreads.setGroupingUsed(false);
        numberformat_maxthreads.setMaximumIntegerDigits(3);
        textField_maxthreads = new JFormattedTextField(numberformat_maxthreads);
        textField_maxthreads.setBounds(120, 129, 87, 25);
        panel.add(textField_maxthreads);
        // 设定默认值
        textField_maxthreads.setValue(FTConfig.getTaskThreadNum());

        JLabel label_threads_tip = new JLabel("（调整范围：1~" + FTConfig.DEFAULT_MAX_TASK_THREAD_NUM + "，默认为30）");
        label_threads_tip.setBounds(217, 129, 417, 25);
        panel.add(label_threads_tip);

        JLabel label_buffersize = new JLabel("文件读写缓冲：");
        label_buffersize.setBounds(10, 185, 105, 25);
        panel.add(label_buffersize);

        // 缓冲大小输入框
        //设定输入格式
        NumberFormat numberformat_buffersize = NumberFormat.getNumberInstance();
        numberformat_buffersize.setGroupingUsed(false);
        numberformat_buffersize.setMaximumIntegerDigits(6);
        textField_buffersize = new JFormattedTextField(numberformat_buffersize);
        textField_buffersize.setBounds(120, 185, 87, 25);
        panel.add(textField_buffersize);
        // 设定默认值
        textField_buffersize.setValue(FTConfig.getStreamBufferSize());

        JLabel label_buffersize_tip = new JLabel("KiB （默认128KiB，缓冲大小决定传输速度，但受到带宽和磁盘性能影响）");
        label_buffersize_tip.setBounds(217, 185, 417, 25);
        panel.add(label_buffersize_tip);

        JLabel label_configpath = new JLabel("（修改无效）");
        label_configpath.setBounds(562, 25, 72, 25);
        panel.add(label_configpath);


        // 加载配置
        loadConfig();

        // 显示窗口，阻塞主面板
        setVisible(true);

    }

    /**
     * 创建证书
     */
    private void createSsl() {
        String passkey = textField_keypass.getText();
        if (StringTools.isBlank(passkey)) {
            FTUITools.showDialogError(this, "错误", "请输入证书密码");
            return;
        }

        btnNewButton_createssl.setEnabled(false);
        textField_keypass.setEnabled(false);
        final String obtnNewButton_createssl = btnNewButton_createssl.getText();
        btnNewButton_createssl.setText("证书生成中....");

        // =====创建证书=====
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {

                KeyInfo keyInfo = FTConfig.getKeyInfo();
                keyInfo.setKeypass(passkey);
                try {
                    // 保存密码
                    String keypass = textField_keypass.getText();
                    FTConfig.setSslKeyPass(keypass);
                    // 生成证书
                    SSLTools.makeSslFile(keyInfo);

                    // 提示成功
                    FTUITools.showDialogInfo(instence, "消息", "证书创建成功");
                } catch (Exception e) {
                    e.printStackTrace();
                    FTUITools.showDialogError(instence, "错误", "证书创建失败：" + e.getMessage());
                }
                // 还原按钮可用
                btnNewButton_createssl.setEnabled(true);
                textField_keypass.setEnabled(true);
                btnNewButton_createssl.setText(obtnNewButton_createssl);
            }
        });

    }

    /**
     * 加载配置
     */
    public void loadConfig() {
        // 配置文件路径
        String configpath = FTConfig.getConfigPath();
        textField_confipath.setText(configpath);
        textField_confipath.setToolTipText(configpath);

        // 获取默认密码
        String keypass = FTConfig.getSslKeyPass();
        textField_keypass.setText(keypass);

        // 任务数
        int threads = FTConfig.getTaskThreadNum();
        textField_maxthreads.setText(threads + "");

    }

    /**
     * 保存配置
     */
    public boolean saveConfig() {
        try {
            // 证书密码
            String keypass = textField_keypass.getText();
            // 更新ssl密码缓存
            FTConfig.setSslKeyPass(keypass);

            // 保存任务数
            String threads = textField_maxthreads.getText();
            if (StringTools.isBlank(threads)) {
                FTUITools.showDialogError(this, "错误", "请输入并行任务数");
                return false;
            } else if (Integer.parseInt(threads) <= 0) {
                FTUITools.showDialogError(this, "错误", "并行任务数必须为大于0的整数");
                return false;
            } else if (Integer.parseInt(threads) > FTConfig.DEFAULT_MAX_TASK_THREAD_NUM) {
                FTUITools.showDialogError(this, "错误", "并行任务数最大为" + FTConfig.DEFAULT_MAX_TASK_THREAD_NUM + "，请修改");
                return false;
            }
            FTConfig.setTaskThreadNum(Integer.parseInt(threads));

            // 缓冲大小
            String buffersize = textField_buffersize.getText();
            if (StringTools.isBlank(buffersize)) {
                FTUITools.showDialogError(this, "错误", "请输入文件读写缓冲");
                return false;
            } else if (Integer.parseInt(buffersize) <= 0) {
                FTUITools.showDialogError(this, "错误", "文件读写缓冲值必须为大于0的整数");
                return false;
            }
            FTConfig.setStreamBufferSize(Integer.parseInt(buffersize));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            FTUITools.showDialogError(this, "错误", "保存出错：" + e.getMessage());
            return false;
        }

    }

    public void closeInstance() {
        instence.dispose();
    }
}
